package com.zjh.photoshopstudy.app.download;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.lzy.okserver.task.XExecutor;
import com.zjh.photoshopstudy.Model.VideoEntity;
import com.zjh.photoshopstudy.R;
import com.zjh.photoshopstudy.Utils.Data;
import com.zjh.photoshopstudy.app.history.onItemCheck;
import com.zjh.photoshopstudy.app.video.VideoActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DownloadAdapter extends RecyclerView.Adapter<DownloadAdapter.DownloadView> {
    static final int TYPE_VIDEO = 0;
    static final int TYPE_MATERIA = 1;

    private int type;
    private boolean isSelect = false;
    private boolean isSelectAll = false;
    private com.zjh.photoshopstudy.app.history.onItemCheck onItemCheck;
    private XExecutor.OnAllTaskEndListener OnAllTaskEndListener;

    private List<DownloadTask> values = new ArrayList<>();
    private Context mContext;

    public void setSelect(boolean select) {
        isSelect = select;
    }

    public boolean isSelect() {
        return isSelect;
    }

    public void setIsSelectAll(boolean b) {
        isSelectAll = b;
    }

    public DownloadAdapter(Context context, onItemCheck onItemCheck) {
        this.mContext = context;
        this.onItemCheck = onItemCheck;
    }

    void updateData(int type) {
        //这里是将数据库的数据恢复
        this.type = type;
        values.clear();
        List<DownloadTask> list = OkDownload.restore(DownloadManager.getInstance().getFinished());
        for (DownloadTask task : list) {
            Progress progress = task.progress;
            if (type == TYPE_VIDEO && progress.extra1 instanceof VideoEntity) {
                values.add(task);
            } else if (type == TYPE_MATERIA && progress.extra2 instanceof VideoEntity) {
                values.add(task);
            }
        }
        List<DownloadTask> list2 = OkDownload.restore(DownloadManager.getInstance().getDownloading());
        for (DownloadTask task : list2) {
            Progress progress = task.progress;
            if (type == TYPE_VIDEO && progress.extra1 instanceof VideoEntity) {
                task.register(new ListDownloadListener(task.progress.tag));
            } else if (type == TYPE_MATERIA && progress.extra2 instanceof VideoEntity) {
                task.register(new ListDownloadListener(task.progress.tag));
            }
        }
        OnAllTaskEndListener.onAllTaskEnd();
        notifyDataSetChanged();

    }

    @NonNull
    @Override
    public DownloadView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new DownloadView(LayoutInflater.from(parent.getContext()).inflate(R.layout.collection_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull final DownloadView holder, final int position) {
        final Progress progress = values.get(position).progress;
        final VideoEntity entity;
        if (type == TYPE_VIDEO) {
            entity = (VideoEntity) progress.extra1;
            Glide.with(mContext).load(Data.webRoot_URL + entity.getvThumbnailPath()).into(holder.mImage);
        } else {
            entity = (VideoEntity) progress.extra2;
        }
        Glide.with(mContext).load(Data.webRoot_URL + entity.getvAppUserEntity().getuIcon()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(holder.mUserImage);
        holder.mName.setText(entity.getvAppUserEntity().getuName());
        holder.mTitle.setText(entity.getvTitle());
        if (isSelect) {
            holder.checkBox.setVisibility(View.VISIBLE);
            if (isSelectAll) {
                holder.checkBox.setChecked(true);
            } else {
                holder.checkBox.setChecked(false);
            }
        } else {
            holder.checkBox.setVisibility(View.INVISIBLE);
            holder.checkBox.setChecked(false);
        }

        holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    onItemCheck.onItemCheck(values.get(position));
                } else {
                    onItemCheck.onItemCancelCheck(values.get(position));
                }
            }
        });
        holder.layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isSelect) {
                    if (type == TYPE_VIDEO) {
                        Intent intent = new Intent(mContext, VideoActivity.class);
                        intent.putExtra("videoEntity", entity);
                        mContext.startActivity(intent);
                    } else {
                        Uri uri = Uri.parse("file://" + progress.filePath);
                        Intent intent = new Intent();
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setAction(Intent.ACTION_VIEW);
                        String type = getMIMEType(progress.filePath);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            uri = FileProvider.getUriForFile(mContext, "com.zjh.photoshopstudy.fileprovider", new File(progress.filePath));
                        }
                        intent.setDataAndType(uri, type);
                        if (!type.equals("*/*")) {
                            mContext.startActivity(intent);
                        } else {
                            mContext.startActivity(showOpenTypeDialog(progress.filePath));
                        }
                    }
                } else {
                    holder.checkBox.setChecked(true);
                }
            }

        });
        holder.size.setText(Formatter.formatFileSize(mContext, progress.totalSize));
    }

    public static Intent showOpenTypeDialog(String param) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "*/*");
        return intent;
    }


    public static String getMIMEType(String filePath) {
        String type = "*/*";
        String fName = filePath;

        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }

        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end == "") {
            return type;
        }

        for (int i = 0; i < Data.MIME_MapTable.length; i++) {
            if (end.equals(Data.MIME_MapTable[i][0])) {
                type = Data.MIME_MapTable[i][1];
            }
        }
        return type;
    }

    @Override
    public int getItemCount() {
        return values.size();
    }

    public void addOnAllTaskEndListener(XExecutor.OnAllTaskEndListener OnAllTaskEndListener) {
        this.OnAllTaskEndListener = OnAllTaskEndListener;
    }


    public class DownloadView extends RecyclerView.ViewHolder {
        ConstraintLayout layout;
        ImageView mImage;
        ImageView mUserImage;
        TextView mTitle;
        TextView mName;
        TextView size;
        CheckBox checkBox;


        public DownloadView(@NonNull View itemView) {
            super(itemView);
            mImage = itemView.findViewById(R.id.imageView4);
            mUserImage = itemView.findViewById(R.id.collection_uicon);
            mTitle = itemView.findViewById(R.id.title2);
            mName = itemView.findViewById(R.id.collection_name);
            layout = itemView.findViewById(R.id.collection_item);
            checkBox = itemView.findViewById(R.id.checkBox2);
            size = itemView.findViewById(R.id.size);
            size.setVisibility(View.VISIBLE);
        }
    }

    private class ListDownloadListener extends DownloadListener {

        ListDownloadListener(Object tag) {
            super(tag);
        }

        @Override
        public void onStart(Progress progress) {
        }

        @Override
        public void onProgress(Progress progress) {
        }

        @Override
        public void onError(Progress progress) {
        }

        @Override
        public void onFinish(File file, Progress progress) {
            Toast.makeText(mContext, "下载完成:" + progress.filePath, Toast.LENGTH_SHORT).show();
            updateData(type);
        }

        @Override
        public void onRemove(Progress progress) {
        }
    }
}
